package cn.e3mall.sso.service.impl;

import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import cn.e3mall.common.jedis.JedisClient;
import cn.e3mall.common.utils.E3Result;
import cn.e3mall.common.utils.JsonUtils;
import cn.e3mall.mapper.TbUserMapper;
import cn.e3mall.pojo.TbUser;
import cn.e3mall.pojo.TbUserExample;
import cn.e3mall.pojo.TbUserExample.Criteria;
import cn.e3mall.sso.service.LoginService;

@Service
public class LoginServiceImpl implements LoginService{

	@Autowired
	private TbUserMapper userMapper;
	
	@Autowired
	private JedisClient jedisClient;
	
	@Value("${TOKEN_EXPIRE_TIME}")
	private Integer TOKEN_EXPIRE_TIME;	
	
	@Override
	public E3Result login(String username, String password) {
		TbUserExample example = new TbUserExample();
		
		Criteria  criteria = example.createCriteria();

		//设置条件
		criteria.andUsernameEqualTo(username);
		//查询数据库用户是否存在
		List<TbUser> list = userMapper.selectByExample(example);
		
		//不存在返回错误信息
		if(list == null || list.size() == 0)	return E3Result.build(400,"用户不存在");
		
		//设置密码为md5与数据库密码比较
		String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
		
		TbUser user = list.get(0);
		
		//不同则返回错误信息
		if( !md5Password.equals(user.getPassword()) )	return E3Result.build(400,"密码错误");
		
		//生成token
		String token = UUID.randomUUID().toString();
		
		//将密码设置为空的目的是，用户有可能需要获取自己的相关信息时，就不需要查询数据库，直接从redis中查
		user.setPassword(null);
		
		//将用户信息保存到redis中
		jedisClient.set("SessionId:"+token, JsonUtils.objectToJson(user));
		
		//设置过期token的过期时间
		jedisClient.expire("SessionId:"+token, TOKEN_EXPIRE_TIME);
		
		//返回结果
		return E3Result.ok(token);
	}


}
